package com.lvjian.community.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.lvjian.community.service.UserAssociationRoleService;
import com.lvjian.community.service.UserLoginService;
import com.lvjian.community.utils.Consts;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登录Controller
 */
@RestController
public class UserLoginController {

    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private UserAssociationRoleService userAssociationRoleService;

    // 判断是否登录成功
    @RequestMapping(value = "/login/status", method = RequestMethod.POST)
    @ResponseBody
    public Object loginStatus(HttpServletRequest request, HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        try {
            String name = request.getParameter("name");
            String password = request.getParameter("password");
            boolean flag = userLoginService.verifyPassword(name, password);
            int userId = userLoginService.selectUserId(name);
            int roleId = userAssociationRoleService.selectRoleId(userId);
            if (flag) {
                userLoginService.updateLastLoginAt(name);
                jsonObject.put(Consts.CODE, 1);
                jsonObject.put(Consts.MSG, "登陆成功");
                jsonObject.put(Consts.ROLE, roleId);
                session.setAttribute(Consts.NAME, name);
            } else {
                jsonObject.put(Consts.CODE, 0);
                jsonObject.put(Consts.MSG, "用户名或密码错误");
            }
        } catch (Exception e) {
            jsonObject.put(Consts.CODE, 0);
            jsonObject.put(Consts.MSG, e.toString());
        }
        return jsonObject;
    }

}
